package com.peter.recyclerviewdemo;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.os.Bundle;
import android.view.View;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    @Nullable
    RecyclerView rv;

    @Nullable
    List<TestData> testDataList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        rv = findViewById(R.id.list_main);

        testDataList = new ArrayList<TestData>() {{
            add(new TestData());
            add(new TestData());
        }};

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        rv.setLayoutManager(layoutManager);
        adapter = new TestAdapter(testDataList);
        rv.setAdapter(adapter);
    }

    @Nullable
    TestAdapter adapter;

    public void RVItemClick(View view) {
        // 获取itemView的位置
        if (rv != null) {
            int position = rv.getChildAdapterPosition(view);
            Toast.makeText(MainActivity.this, "点击了 " + testDataList.get(position),
                    Toast.LENGTH_SHORT).show();
            // 0 1 2 3 4 5
            testDataList.add(new TestData());
            if (adapter != null) {
                adapter.notifyItemRangeInserted(position, 1);
            }
        }
    }

}